﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;

public class MonsterManager : MonoBehaviour
{
    GameObject monster1Prefab;
    public List<GameObject> monsterList;
    Transform curScene;
    Transform curTargetPlayer;
    Vector3 birthPos;
    float timer = 5f;

    private void Awake()
    {
        birthPos = new Vector3(2, -2.5f, 0);
        monster1Prefab = Resources.Load("Prefabs/monster2") as GameObject;
        monsterList = new List<GameObject>();

    }

    // Start is called before the first frame update
    void Start()
    {        
        curScene = GameObject.Find("RightScene").transform;
        curTargetPlayer = GameObject.Find("Player2").transform;
    }

    // Update is called once per frame
    void Update()
    {
        if (timer < 0) {
            timer = 10f;
            //addMonster();
        }
        timer -= Time.deltaTime;
    }

    public void changeScene(Transform scene, Transform targetPlayer) {        
        curScene = scene;
        curTargetPlayer = targetPlayer;
        for (int i = 0; i < monsterList.Count; ++i) {
            if (monsterList[i] != null)
            {
                Vector3 localPos = monsterList[i].transform.localPosition;
                monsterList[i].transform.parent = scene;
                monsterList[i].transform.localPosition = localPos;
                AIDestinationSetter aiDestinationSetter = monsterList[i].GetComponent<AIDestinationSetter>();
                aiDestinationSetter.target = targetPlayer;
            }
        }
    }

    public void changeTarget(Transform targetPlayer) {
        curTargetPlayer = targetPlayer;
        for (int i = 0; i < monsterList.Count; ++i)
        {
            if (monsterList[i] != null)
            {
                AIDestinationSetter aiDestinationSetter = monsterList[i].GetComponent<AIDestinationSetter>();
                aiDestinationSetter.target = targetPlayer;
            }
        }
    }

    public void addMonster(Vector3 pos) {
        GameObject monster = GameObject.Instantiate(monster1Prefab);
        monster.GetComponent<MonsterController>().setSpeed(1.0f + 2 * Random.value);
        monster.transform.parent = curScene;
        monster.transform.localPosition = new Vector3(pos.x + Random.value, pos.y + Random.value, Random.value);
        monster.GetComponent<AIDestinationSetter>().target = curTargetPlayer;
        monsterList.Add(monster);
    }
    
}
